<?php

define('INFANTRY', 1);
define('ARCHER', 2);
define('CAVALRY', 3);

class unit
{
    protected $power;
    protected $type;
    protected $level;
    protected $quantity;
    protected $name;
    protected $is_invocation;

    public function  __construct($power, $type, $level, $quantity = 0, $name = NULL, $is_invocation = FALSE)
    {
        $this->power = $power;
        $this->type = $type;
        $this->level = $level;
        $this->quantity = $quantity;
        if ($name === NULL)
        {
            $this->name = self::type_to_name($type);
        }
        else
        {
            $this->name = $name;
        }
        $this->is_invocation = $is_invocation;
    }

    public function __get($field)
    {
        if (in_array($field, array('power', 'type', 'level', 'quantity', 'name')))
        {
            return $this->$field;
        }
        throw new Exception("cannot access to field $field");
    }

    public function __set($field, $value)
    {
        if ($field != 'quantity')
        {
            throw new Exception("cannot access to field $field");
        }
        $this->quantity = $value;
    }

    public static function type_to_name($type)
    {
        return ($type == INFANTRY) ? 'Infantry' :
            (($type == ARCHER) ? 'Archer' : 'Cavalry');
    }

    public function get_xp()
    {
        $divisor = (($this->level == 7) ? 10 :
            (($this->level >= 4) ? 12 : 15));
        return ($this->power * $this->quantity) / $divisor;
    }

    public function get_attack_type_bonus($defend_type)
    {
        if ($this->type == ARCHER && $defend_type == INFANTRY ||
            $this->type == INFANTRY && $defend_type == CAVALRY ||
            $this->type == CAVALRY && $defend_type == ARCHER)
        {
            return 0.5;
        }
        return 0;
    }
}

?>
